package com.wechatFriendExportTool.utils;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import java.util.ArrayList;
import java.util.List;

public class EnhancedWeChatSwitcher {
    
    // 微信可能的窗口类名
    private static final String[] WECHAT_CLASS_NAMES = {
        "WeChatMainWndForPC", 
        "WeChat", 
        "WeChatMainWnd"
    };
    
    // 微信可能的窗口标题关键词
    private static final String[] WECHAT_TITLE_KEYWORDS = {
        "微信", 
        "WeChat", 
        "Chat", 
        "微信 for Windows"
    };
    
    /**
     * 增强的微信窗口查找和切换
     */
    public static boolean enhancedSwitchToWeChat() {
        System.out.println("开始查找微信窗口...");
        
        List<WindowInfo> wechatWindows = findAllWeChatWindows();
        
        if (wechatWindows.isEmpty()) {
            System.out.println("未找到任何微信窗口");
            // 检查微信进程是否运行
            if (isWeChatProcessRunning()) {
                System.out.println("微信进程在运行，但未找到窗口，可能是隐藏状态");
                // 尝试通过进程激活
                return activateWeChatByProcess();
            } else {
                System.out.println("微信进程未运行");
                return false;
            }
        }
        
        System.out.println("找到 " + wechatWindows.size() + " 个可能的微信窗口:");
        for (WindowInfo info : wechatWindows) {
            System.out.println("  - 标题: '" + info.title + "', 类名: '" + info.className + "'");
        }
        
        // 尝试激活最可能是主窗口的窗口
        for (WindowInfo info : wechatWindows) {
            if (isLikelyMainWindow(info)) {
                System.out.println("尝试激活主窗口: " + info.title);
                if (activateWindow(info.hwnd)) {
                    return true;
                }
            }
        }
        
        // 如果主窗口激活失败，尝试其他窗口
        for (WindowInfo info : wechatWindows) {
            if (activateWindow(info.hwnd)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 查找所有可能的微信窗口
     */
    private static List<WindowInfo> findAllWeChatWindows() {
        final List<WindowInfo> windows = new ArrayList<>();
        
        User32.INSTANCE.EnumWindows(new WinUser.WNDENUMPROC() {
            @Override
            public boolean callback(WinDef.HWND hwnd, Pointer pointer) {
                if (!User32.INSTANCE.IsWindowVisible(hwnd)) {
                    return true; // 跳过不可见窗口
                }
                
                // 获取窗口标题
                char[] windowText = new char[1024];
                User32.INSTANCE.GetWindowText(hwnd, windowText, 1024);
                String title = Native.toString(windowText).trim();
                
                if (title.isEmpty()) {
                    return true; // 跳过无标题窗口
                }
                
                // 获取窗口类名
                char[] className = new char[256];
                User32.INSTANCE.GetClassName(hwnd, className, 256);
                String classNameStr = Native.toString(className);
                
                // 检查是否是微信窗口
                if (isWeChatWindow(title, classNameStr)) {
                    windows.add(new WindowInfo(hwnd, title, classNameStr));
                }
                
                return true;
            }
        }, null);
        
        return windows;
    }
    
    /**
     * 判断是否为微信窗口
     */
    private static boolean isWeChatWindow(String title, String className) {
        // 检查类名
        for (String classKeyword : WECHAT_CLASS_NAMES) {
            if (className.contains(classKeyword)) {
                return true;
            }
        }
      /*
        // 检查标题
        for (String titleKeyword : WECHAT_TITLE_KEYWORDS) {
            if (title.contains(titleKeyword)) {
                return true;
            }
        }*/
        
        return false;
    }
    
    /**
     * 判断是否可能是主窗口
     */
    private static boolean isLikelyMainWindow(WindowInfo info) {
        String title = info.title.toLowerCase();
        String className = info.className.toLowerCase();
        
        // 主窗口通常有特定的特征
        return (title.contains("微信") && !title.contains("登录")) ||
               className.contains("main") ||
               title.length() <= 10; // 主窗口标题通常较短
    }
    
    /**
     * 激活窗口的增强方法
     */
    private static boolean activateWindow(WinDef.HWND hwnd) {
        try {
           /* // 方法1: 标准方法
            if (User32.INSTANCE.SetForegroundWindow(hwnd)) {
                System.out.println("SetForegroundWindow 成功");
                return true;
            }*/
            
            // 方法2: 先显示窗口
            User32.INSTANCE.ShowWindow(hwnd, WinUser.SW_SHOW);
            User32.INSTANCE.ShowWindow(hwnd, WinUser.SW_RESTORE);
            

            
            // 方法4: 模拟Alt+空格然后按X（最大化/还原）
            simulateWindowActivation();
            
            Thread.sleep(100); // 给窗口时间响应
            
            // 再次尝试
            return User32.INSTANCE.SetForegroundWindow(hwnd);
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 模拟按键激活窗口
     */
    private static void simulateWindowActivation() {
        try {
            java.awt.Robot robot = new java.awt.Robot();
            
            // Alt+空格打开系统菜单，然后按X最大化/还原
            robot.keyPress(java.awt.event.KeyEvent.VK_ALT);
            robot.keyPress(java.awt.event.KeyEvent.VK_SPACE);
            robot.delay(50);
            robot.keyRelease(java.awt.event.KeyEvent.VK_SPACE);
            robot.keyRelease(java.awt.event.KeyEvent.VK_ALT);
            
            robot.delay(100);
            
            robot.keyPress(java.awt.event.KeyEvent.VK_X);
            robot.delay(50);
            robot.keyRelease(java.awt.event.KeyEvent.VK_X);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 检查微信进程是否运行
     */
    private static boolean isWeChatProcessRunning() {
        try {
            Process process = Runtime.getRuntime().exec("tasklist /fi \"imagename eq WeChat.exe\"");
            java.util.Scanner scanner = new java.util.Scanner(process.getInputStream());
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.contains("WeChat.exe") && !line.contains("信息")) {
                    scanner.close();
                    return true;
                }
            }
            scanner.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    /**
     * 通过进程激活微信
     */
    private static boolean activateWeChatByProcess() {
        try {
            // 使用PowerShell激活进程
            String powerShellCommand = 
                "Get-Process WeChat -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowTitle } | ForEach-Object { Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.Interaction]::AppActivate($_.Id) }";
            
            Process process = Runtime.getRuntime().exec(new String[] {
                "powershell", "-Command", powerShellCommand
            });
            
            return process.waitFor() == 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 窗口信息类
     */
    private static class WindowInfo {
        WinDef.HWND hwnd;
        String title;
        String className;
        
        WindowInfo(WinDef.HWND hwnd, String title, String className) {
            this.hwnd = hwnd;
            this.title = title;
            this.className = className;
        }
    }
    
    public static void main(String[] args) {
        boolean success = enhancedSwitchToWeChat();
        System.out.println("切换结果: " + (success ? "成功" : "失败"));
        
        if (!success) {
            System.out.println("建议:");
            System.out.println("1. 确保微信正在运行");
            System.out.println("2. 检查微信窗口是否最小化到系统托盘");
            System.out.println("3. 尝试手动点击微信窗口一次，然后重试");
        }
    }
}